const Service = require('egg').Service;

class OrderService extends Service {
    // 创建订单
    async create(orderData) {
        const { ctx } = this;

        // 检查商品是否存在
        const good = await ctx.model.Good.findByPk(orderData.goods_id);
        if (!good) {
            throw new Error('商品不存在');
        }

        // 检查卖家是否存在
        const seller = await ctx.model.User.findByPk(orderData.seller_id);
        if (!seller) {
            throw new Error('卖家不存在');
        }

        // 检查买家是否存在
        const buyer = await ctx.model.User.findByPk(orderData.buyer_id);
        if (!buyer) {
            throw new Error('买家不存在');
        }

        // 不能购买自己的商品
        if (orderData.buyer_id === orderData.seller_id) {
            throw new Error('不能购买自己的商品');
        }

        // 检查商品状态
        if (good.status !== 1) {
            throw new Error('商品已下架或不存在');
        }

        // 创建订单
        const order = await ctx.model.Order.create({
            ...orderData,
            created_at: new Date(),
            updated_at: new Date(),
        });

        // 更新商品状态为已售出
        await good.update({
            status: 2, // 2表示已售出
            updated_at: new Date()
        });

        return await this.getOrderDetail(order.order_id);
    }

    // 获取订单详情
    async getOrderDetail(orderId) {
        const { ctx } = this;

        const order = await ctx.model.Order.findByPk(orderId, {
            include: [
                {
                    model: ctx.model.User,
                    as: 'buyer',
                    attributes: ['user_id', 'nickname', 'avatar', 'phone']
                },
                {
                    model: ctx.model.User,
                    as: 'seller',
                    attributes: ['user_id', 'nickname', 'avatar', 'phone']
                },
                {
                    model: ctx.model.Good,
                    as: 'good',
                    attributes: ['item_id', 'title', 'description', 'price', 'images']
                }
            ]
        });

        if (!order) {
            throw new Error('订单不存在');
        }

        return order;
    }

    // 获取订单列表（分页 + 基础搜索）
    async getOrders(query) {
        const { ctx } = this;
        const {
            page = 1,
            pageSize = 10,
            keyword, // 新增：搜索关键词
            ...where
        } = query;

        const options = {
            where,
            limit: parseInt(pageSize),
            offset: (parseInt(page) - 1) * parseInt(pageSize),
            include: [
                {
                    model: ctx.model.User,
                    as: 'buyer',
                    attributes: ['user_id', 'nickname', 'avatar']
                },
                {
                    model: ctx.model.User,
                    as: 'seller',
                    attributes: ['user_id', 'nickname', 'avatar']
                },
                {
                    model: ctx.model.Good,
                    as: 'good',
                    attributes: ['item_id', 'title', 'price', 'images']
                }
            ],
            order: [['created_at', 'DESC']]
        };

        // 新增：模糊查询逻辑
        if (keyword) {
            const keywordConditions = [];

            // 订单ID精确查询
            if (!isNaN(keyword)) {
                keywordConditions.push({
                    order_id: parseInt(keyword)
                });
            }

            // 商品标题和描述模糊查询
            keywordConditions.push({
                '$good.title$': { [ctx.model.Sequelize.Op.like]: `%${keyword}%` }
            });

            keywordConditions.push({
                '$good.description$': { [ctx.model.Sequelize.Op.like]: `%${keyword}%` }
            });

            // 买家昵称模糊查询
            keywordConditions.push({
                '$buyer.nickname$': { [ctx.model.Sequelize.Op.like]: `%${keyword}%` }
            });

            // 卖家昵称模糊查询
            keywordConditions.push({
                '$seller.nickname$': { [ctx.model.Sequelize.Op.like]: `%${keyword}%` }
            });

            options.where[ctx.model.Sequelize.Op.or] = keywordConditions;
        }

        const { count, rows } = await ctx.model.Order.findAndCountAll(options);

        return {
            list: rows,
            pagination: {
                page: parseInt(page),
                pageSize: parseInt(pageSize),
                total: count,
                totalPages: Math.ceil(count / pageSize)
            }
        };
    }

    // 高级搜索订单（支持多条件筛选）
    async searchOrders(searchParams) {
        const { ctx } = this;
        const {
            page = 1,
            pageSize = 10,
            keyword,
            status,
            buyer_name,
            seller_name,
            goods_title,
            start_date,
            end_date,
            min_amount,
            max_amount,
            order_by = 'created_at',
            order_type = 'DESC'
        } = searchParams;

        const options = {
            limit: parseInt(pageSize),
            offset: (parseInt(page) - 1) * parseInt(pageSize),
            include: [
                {
                    model: ctx.model.User,
                    as: 'buyer',
                    attributes: ['user_id', 'nickname', 'avatar', 'phone']
                },
                {
                    model: ctx.model.User,
                    as: 'seller',
                    attributes: ['user_id', 'nickname', 'avatar', 'phone']
                },
                {
                    model: ctx.model.Good,
                    as: 'good',
                    attributes: ['item_id', 'title', 'description', 'price', 'images', 'category']
                }
            ],
            order: [[order_by, order_type.toUpperCase()]],
            where: {}
        };

        // 状态筛选
        if (status !== undefined && status !== '') {
            options.where.status = parseInt(status);
        }

        // 金额范围筛选
        if (min_amount !== undefined || max_amount !== undefined) {
            options.where.amount = {};
            if (min_amount !== undefined) {
                options.where.amount[ctx.model.Sequelize.Op.gte] = parseFloat(min_amount);
            }
            if (max_amount !== undefined) {
                options.where.amount[ctx.model.Sequelize.Op.lte] = parseFloat(max_amount);
            }
        }

        // 时间范围筛选
        if (start_date || end_date) {
            options.where.created_at = {};
            if (start_date) {
                const startDate = new Date(start_date);
                startDate.setHours(0, 0, 0, 0);
                options.where.created_at[ctx.model.Sequelize.Op.gte] = startDate;
            }
            if (end_date) {
                const endDate = new Date(end_date);
                endDate.setHours(23, 59, 59, 999);
                options.where.created_at[ctx.model.Sequelize.Op.lte] = endDate;
            }
        }

        // 关键词模糊查询
        if (keyword) {
            const keywordConditions = [];

            // 订单ID精确查询
            if (!isNaN(keyword)) {
                keywordConditions.push({
                    order_id: parseInt(keyword)
                });
            }

            // 商品标题和描述模糊查询
            keywordConditions.push({
                '$good.title$': { [ctx.model.Sequelize.Op.like]: `%${keyword}%` }
            });

            keywordConditions.push({
                '$good.description$': { [ctx.model.Sequelize.Op.like]: `%${keyword}%` }
            });

            // 买家昵称模糊查询
            keywordConditions.push({
                '$buyer.nickname$': { [ctx.model.Sequelize.Op.like]: `%${keyword}%` }
            });

            // 卖家昵称模糊查询
            keywordConditions.push({
                '$seller.nickname$': { [ctx.model.Sequelize.Op.like]: `%${keyword}%` }
            });

            options.where[ctx.model.Sequelize.Op.or] = keywordConditions;
        }

        // 独立的买家名称筛选
        if (buyer_name) {
            options.include[0].where = {
                ...options.include[0].where,
                nickname: { [ctx.model.Sequelize.Op.like]: `%${buyer_name}%` }
            };
        }

        // 独立的卖家名称筛选
        if (seller_name) {
            options.include[1].where = {
                ...options.include[1].where,
                nickname: { [ctx.model.Sequelize.Op.like]: `%${seller_name}%` }
            };
        }

        // 独立的商品标题筛选
        if (goods_title) {
            options.include[2].where = {
                ...options.include[2].where,
                title: { [ctx.model.Sequelize.Op.like]: `%${goods_title}%` }
            };
        }

        const { count, rows } = await ctx.model.Order.findAndCountAll(options);

        return {
            list: rows,
            pagination: {
                page: parseInt(page),
                pageSize: parseInt(pageSize),
                total: count,
                totalPages: Math.ceil(count / pageSize)
            }
        };
    }

    // 获取我的订单（买家或卖家）- 支持搜索
    async getMyOrders(userId, role = 'buyer', searchParams = {}) {
        const { ctx } = this;
        const { keyword, status, page = 1, pageSize = 10 } = searchParams;

        const where = role === 'buyer' ? { buyer_id: userId } : { seller_id: userId };

        // 状态筛选
        if (status !== undefined && status !== '') {
            where.status = parseInt(status);
        }

        const options = {
            where,
            limit: parseInt(pageSize),
            offset: (parseInt(page) - 1) * parseInt(pageSize),
            include: [
                {
                    model: ctx.model.User,
                    as: 'buyer',
                    attributes: ['user_id', 'nickname', 'avatar', 'phone']
                },
                {
                    model: ctx.model.User,
                    as: 'seller',
                    attributes: ['user_id', 'nickname', 'avatar', 'phone']
                },
                {
                    model: ctx.model.Good,
                    as: 'good',
                    attributes: ['item_id', 'title', 'description', 'price', 'images', 'category']
                }
            ],
            order: [['created_at', 'DESC']]
        };

        // 关键词搜索
        if (keyword) {
            const keywordConditions = [];

            // 订单ID精确查询
            if (!isNaN(keyword)) {
                keywordConditions.push({
                    order_id: parseInt(keyword)
                });
            }

            // 商品标题模糊查询
            keywordConditions.push({
                '$good.title$': { [ctx.model.Sequelize.Op.like]: `%${keyword}%` }
            });

            // 对方用户昵称模糊查询
            if (role === 'buyer') {
                keywordConditions.push({
                    '$seller.nickname$': { [ctx.model.Sequelize.Op.like]: `%${keyword}%` }
                });
            } else {
                keywordConditions.push({
                    '$buyer.nickname$': { [ctx.model.Sequelize.Op.like]: `%${keyword}%` }
                });
            }

            options.where[ctx.model.Sequelize.Op.and] = [
                where,
                { [ctx.model.Sequelize.Op.or]: keywordConditions }
            ];
        }

        const { count, rows } = await ctx.model.Order.findAndCountAll(options);

        return {
            list: rows,
            pagination: {
                page: parseInt(page),
                pageSize: parseInt(pageSize),
                total: count,
                totalPages: Math.ceil(count / pageSize)
            }
        };
    }

    // 获取订单统计
    async getOrderStats(userId) {
        const { ctx } = this;

        const buyerStats = await ctx.model.Order.findAll({
            where: { buyer_id: userId },
            attributes: [
                'status',
                [ctx.model.Sequelize.fn('COUNT', ctx.model.Sequelize.col('order_id')), 'count']
            ],
            group: ['status']
        });

        const sellerStats = await ctx.model.Order.findAll({
            where: { seller_id: userId },
            attributes: [
                'status',
                [ctx.model.Sequelize.fn('COUNT', ctx.model.Sequelize.col('order_id')), 'count']
            ],
            group: ['status']
        });

        return {
            as_buyer: buyerStats,
            as_seller: sellerStats
        };
    }

    // 更新订单状态 - 修复权限检查
    async updateOrderStatus(orderId, status, userId, userType = 'user') {
        const { ctx } = this;

        const order = await ctx.model.Order.findByPk(orderId);
        if (!order) {
            throw new Error('订单不存在');
        }

        // 检查权限：管理员可以更新任何订单状态，普通用户只能更新自己的订单
        if (userType === 'admin') {
            // 管理员有全部权限，直接通过
        } else if (order.buyer_id !== userId && order.seller_id !== userId) {
            throw new Error('无权操作此订单');
        }

        await order.update({
            status,
            updated_at: new Date()
        });

        return await this.getOrderDetail(orderId);
    }

    // 删除订单 - 修复权限检查
    async deleteOrder(orderId, userId, userType = 'user') {
        const { ctx } = this;

        const order = await ctx.model.Order.findByPk(orderId);
        if (!order) {
            throw new Error('订单不存在');
        }

        // 检查权限：管理员可以删除任何订单，普通用户只能删除自己的订单
        if (userType === 'admin') {
            // 管理员有全部权限，直接通过
        } else if (order.buyer_id !== userId && order.seller_id !== userId) {
            throw new Error('无权删除此订单');
        }

        // 只能删除已取消或已完成的订单
        if (order.status !== 0 && order.status !== 4) {
            throw new Error('只能删除已取消或已完成的订单');
        }

        await order.destroy();
        return true;
    }

    // 根据ID获取订单
    async getOrderById(orderId) {
        const { ctx } = this;

        const order = await this.getOrderDetail(orderId);
        if (!order) {
            throw new Error('订单不存在');
        }

        return order;
    }

    // 新增：管理员更新订单状态（无需权限检查）
    async adminUpdateOrderStatus(orderId, status) {
        const { ctx } = this;

        const order = await ctx.model.Order.findByPk(orderId);
        if (!order) {
            throw new Error('订单不存在');
        }

        await order.update({
            status,
            updated_at: new Date()
        });

        return await this.getOrderDetail(orderId);
    }
}

module.exports = OrderService;